package com.liuym.student.resolver;

import com.liuym.common.annotation.StudentLoginUser;
import com.liuym.common.constants.Constants;
import com.liuym.common.exception.StudentException;
import com.liuym.student.repository.model.vo.StudentVO;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

public class StudentLoginUserResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.hasParameterAnnotation(StudentLoginUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        StudentVO user = (StudentVO) nativeWebRequest.getAttribute(Constants.STUDENT_LOGIN_USER, RequestAttributes.SCOPE_REQUEST);
        if (null != user) {
            return user;
        }
        throw StudentException.internalServerError();
    }
}
